const { SuccessModel, ErrorModel } = require('../model/resModel');
const { getCookieExpires } = require('../utils/helper');

const {
  getList,
  getDetail,
} = require('../controler/blog')

const handleBlogRouter = (req, res) => {
  const method = req.method // GET POST

  // 获取博客列表
  if (method === 'GET' && req.path === '/api/blog/list') {
    const author = req.query.author || ''
    const keyword = req.query.keyword || ''
    getList(author, keyword).then(listData => {
      if (req.needSetCookie) {
        const userId = req.cookie.userid;
        res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
      }

      res.end(
        JSON.stringify(new SuccessModel(listData))
      )
    });
    return true;
  }

  // 获取博客详情
  if (method === 'GET' && req.path === '/api/blog/detail') {
    const id = req.query.id
    getDetail(id).then(data => {
      if (req.needSetCookie) {
        const userId = req.cookie.userid;
        res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
      }

      res.end(
        JSON.stringify(new SuccessModel(data))
      )
    });
    return true;
  }

  return false;
}

module.exports = handleBlogRouter;
